<script setup>
import {ref, onMounted, computed} from 'vue'
import { sessionApi, saveBrandApi, proBrandsApi, oneBrandApi, pageBrandsApi, sortBrandApi } from '@/commons/api'
import routes from '@/commons/router'
import Loader from '@/components/loader/Loader'
import { CScrollbar } from 'c-scrollbar'
import Msg from '@/components/message'
import Confirm from '@/components/confirm'
import Pager from '@/components/pager/Pager'
import { formatDatetime } from '@/commons/filter'
import Upload from '@/components/upload/Upload'

const loadShow = ref(false)

// 界面挂载前处理
onMounted(() => {
  // 获取用户会话信息
  checkAuth()
})

let myAuth = {
  saveAuth: false,
  procAuth: false
}
// checkAuth 获取权限
const checkAuth = async () => {
  loadShow.value = true
  try {
    const res = await sessionApi()
    if (res.code === import.meta.env.VITE_SUCCESS_CODE) {
      const userBtnCode = res.data.btnCodes
      myAuth = {
        saveAuth: userBtnCode.indexOf('1003020101') !== -1,
        procAuth: userBtnCode.indexOf('1003020102') !== -1
      }
      await page(0, 1)
    } else {
      localStorage.removeItem("token")
      Msg({ kind: 'error', txt: res.msg })
      routes.replace('/login')
    }
    loadShow.value = false
  } catch (e) {
    loadShow.value = false
    Msg({ kind: 'error', txt: '系统错误，请联系管理员！' + e })
  }
}

const schRef = ref({
  kind: 1,
  keywords: '',
  offset: 0,
  limit: 20
})
const total = ref(0)
const curPage = ref(1)
const brandList = ref([])
const hasData = ref(false)
// page 列表展示
const page = async (offset, cur) => {
  schRef.value.offset = offset || 0
  curPage.value = cur || 1
  hasData.value = false
  const res = await pageBrandsApi(schRef.value)
  if(res.code === import.meta.env.VITE_SUCCESS_CODE && res.data) {
    hasData.value = true
    total.value = res.data.total
    brandList.value = res.data.list
    idList.value = []
    checkList.value = []
    allCheck.value = false
    res.data.list.forEach(() => {
      checkList.value.push(false)
    })
  }
}

// search 筛选
const schShow = ref(false)
const search = () => {
  schShow.value = !schShow.value
}

// clrSch 重置搜索框
const clrSch = () => {
  schRef.value = {
    kind: 1,
    keywords: '',
    offset: 0,
    limit: 20
  }
  page(0, 1)
}

// 选择效果实现
const idList = ref([])
const checkList = ref([])
const allCheck = ref(false)
// checkAll 全选
const checkAll = () => {
  idList.value = []
  checkList.value = []
  allCheck.value = !allCheck.value
  if(allCheck.value) {
    brandList.value.forEach(item => {
      idList.value.push(item.brandId)
      checkList.value.push(true)
    })
  } else {
    brandList.value.forEach(() => {
      checkList.value.push(false)
    })
  }
}
// checkCurId 单选
const checkCurId = (idx, brandId) => {
  if(!checkList.value[idx]) {
    idList.value.push(brandId)
  } else {
    idList.value.splice(idList.value.findIndex(id => id === brandId), 1)
  }
  checkList.value[idx] = !checkList.value[idx]
}

const brandForm = ref({
  brandId: '',
  brandName: '',
  brandCode: '',
  fstChar: '',
  kind: 1,
  sort: 0,
  logoId: '',
  logoName: '',
  logoUrl: '',
  remarks: ''
})
// add 新增
const showModal = ref(false)
const add = () => {
  sort()
  showModal.value = true
}
// update 修改
const update = async (brandId) => {
  const res = await oneBrandApi({ brandId })
  if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
    brandForm.value = res.data
    logoRef.value = { id: res.data.logoId, name: res.data.logoName, url: res.data.logoUrl, thumb: res.data.logoUrl.replace('/img/', '/img/thumb/') }
    showModal.value = true
  } else {
    Msg({ kind: 'info', txt: '暂无内容' })
  }
}
// save 保存提交
const save = async () => {
  let brandName = brandForm.value.brandName
  let brandCode = brandForm.value.brandCode
  let fstChar = brandForm.value.fstChar
  let sort = brandForm.value.sort
  if(brandName === '' || brandName.length > 50) {
    Msg({ kind: 'warn', txt: '名称不能为空，且长度不超过50个字符！' })
    return
  } else if(brandCode === '' || brandCode.length > 30) {
    Msg({ kind: 'warn', txt: '编码不能为空，且长度为30位的数字编码！' })
    return
  } else if(fstChar === '' || fstChar.length !== 1) {
    Msg({ kind: 'warn', txt: '请输入品牌首字母，必须为大写字母！' })
    return
  } else if(sort === 0) {
    Msg({ kind: 'warn', txt: '请输入按钮排序，必须为数字！' })
    return
  }
  brandForm.value.logoId = logoRef.value.id
  brandForm.value.logoName = logoRef.value.name
  brandForm.value.logoUrl = logoRef.value.url
  loadShow.value = true
  try {
    const res = await saveBrandApi(brandForm.value)
    if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
      closeModal()
      await page(0, 1)
      Msg({ kind: 'success', txt: '恭喜您，按钮信息保存成功！' })
    } else {
      Msg({ kind: 'error', txt: res.msg })
    }
    loadShow.value = false
  } catch (e) {
    loadShow.value = false
    Msg({ kind: 'error', txt: '系统错误，请联系管理员！' + e })
  }
}

// closeModal 关闭弹出层，并重置表单数据
const closeModal = () => {
  showModal.value = false
  brandForm.value = {
    brandId: '',
    brandName: '',
    brandCode: '',
    fstChar: '',
    kind: 1,
    sort: 0,
    logoId: '',
    logoName: '',
    logoUrl: '',
    remarks: ''
  }
  logoRef.value = { id: '', name: '', url: '' }
}

// process 处理
const process = async(states) => {
  if(!idList || idList.value.length===0) {
    Msg({ kind: 'warn', txt: '请至少选择一项再处理！' })
    return
  }
  Confirm('确定要操作选中的数据吗？').then(() => {
    proBrands(states)
  }).catch(() => {
    Msg({ kind: 'info', txt: "取消处理选中的数据！" })
  })
}
// proBrands 删除实现，分离出来防止调用时异步报错
const proBrands = async (states) => {
  let ids = idList.value.join(',')
  loadShow.value = true
  try {
    const res = await proBrandsApi({ ids, states })
    if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
      await page(0, 1)
      Msg({ kind: 'success', txt: '恭喜您，品牌处理成功！' })
    } else {
      Msg({ kind: 'error', txt: res.msg })
    }
    loadShow.value = false
  } catch (e) {
    loadShow.value = false
    Msg({ kind: 'error', txt: '系统错误，请联系管理员！' + e })
  }
}

// sort 按钮排序
const sort = async () => {
  const res = await sortBrandApi({ kind: 1 })
  if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
    brandForm.value.sort = res.data
  }
}

// 获取图片路径
const logoRef = ref({ id: '', name: '', url: '' })
const setUrl = (kind, type, file) => {
  logoRef.value = file
  brandForm.value.brandName= file.name
}

// fmtDate 时间戳转时间
const fmtDate = computed(() => {
  return (time) => {
    let date = new Date(time*1000)
    return formatDatetime(date)
  }
})

const fmtState = computed(() => {
  return (states) => {
    let str
    switch (states) {
      case 1:
        str = '已启用'
        break;
      case 3:
        str = '已停用'
        break;
      default:
        str = '其它'
        break
    }
    return str
  }
})
</script>

<template>
  <div class="brand-a">
    <div class="brand-b">
      <div class="brand-c">
        <div v-if="myAuth.saveAuth" class="btn-pi mr15" title="新增" @click="add"><i class="iconfont">&#xea2d;</i> 新增</div>
        <div v-if="myAuth.procAuth" class="btn-de mr15" title="删除" @click="process(2)"><i class="iconfont">&#xea45;</i> 删除</div>
        <div v-if="myAuth.procAuth" class="btn-ds mr15" title="启用" @click="process(1)"><i class="iconfont">&#xea30;</i> 启用</div>
        <div v-if="myAuth.procAuth" class="btn-dw mr15" title="停用" @click="process(3)"><i class="iconfont">&#xea2e;</i> 停用</div>
        <div class="btn-r mr15" title="筛选" @click="search"><i class="iconfont">&#xea49;</i></div>
        <div class="btn-r mr15" title="刷新" @click="page(0, 1)"><i class="iconfont">&#xea8c;</i></div>
      </div>
      <div class="brand-d"><i class="iconfont">&#xeaaa;</i> 当前位置：工作台 > 供应 > 商品管理 > 商品品牌</div>
    </div>
    <div v-show="schShow" class="brand-e">
      <div class="mr15 mt10"><input type="text" v-model="schRef.keywords" maxlength="30" placeholder="请输入关键字" class="sch-ipt" /></div>
      <div class="brand-f mt10">
        <div class="btn-pi mr15" title="搜索" @click="page(0, 1)"><i class="iconfont">&#xea8e;</i> 搜索</div>
        <div class="btn-d" title="重置" @click="clrSch"><i class="iconfont">&#xea4f;</i> 重置</div>
      </div>
    </div>
    <div v-if="hasData">
      <table>
        <tbody>
          <tr>
            <th style="width: 5%;"><span @click="checkAll()" title="全选"><i :class="['iconfont', allCheck ? 'chked' : 'chk']" v-html="allCheck ? '&#xea3a;' : '&#xea46;'" /></span></th>
            <th style="width: 8%;">LOGO</th>
            <th style="width: 17%;">名称</th>
            <th style="width: 13%;">编码</th>
            <th style="width: 10%;">首字母</th>
            <th style="width: 7%;">排序</th>
            <th style="width: 10%;">状态</th>
            <th style="width: 20%;">时间</th>
            <th style="width: 10%;">操作</th>
          </tr>
          <tr v-for="(brand, index) in brandList" :key="brand.brandId" class="tr-style">
            <td class="txt-center"><span @click="checkCurId(index, brand.brandId)" title="选择"><i :class="['iconfont', checkList[index] ? 'chked' : 'chk']" v-html="checkList[index]  ? '&#xe685;' : '&#xe686;'" /></span></td>
            <td class="txt-center"><img v-lazy="brand.logoUrl.replace('/img/', '/img/thumb/')" :alt="brand.logoName" width="90" height="40" /></td>
            <td class="txt-center">{{ brand.brandName }}</td>
            <td class="txt-center">{{ brand.brandCode }}</td>
            <td class="txt-center">{{ brand.fstChar }}</td>
            <td class="txt-center">{{ brand.sort }}</td>
            <td class="txt-center"><span :class="[brand.states===1 ? 'tag-s' : 'tag-e']">{{fmtState(brand.states)}}</span></td>
            <td class="txt-center">{{ fmtDate(brand.addTime) }}</td>
            <td class="txt-center">
              <span v-if="myAuth.saveAuth" class="cl-warn" title="修改" @click="update(brand.brandId)"><i class="iconfont">&#xea48;</i> 修 改</span>
            </td>
          </tr>
        </tbody>
      </table>
      <pager v-if="hasData" :limit="schRef.limit" :total="total" :page="curPage" @turn="page" />
    </div>
    <div v-else class="no-data">暂无内容</div>

    <!-- 新增、修改弹出层 -->
    <transition name="fade-mod" appear>
      <div v-if="showModal" class="modal-backdrop">
        <c-scrollbar>
          <div class="modal" style="width: 600px;">
            <div class="modal-header">
              <div class="header-left"><i class="iconfont">&#xea54;</i> 保存商品品牌</div>
              <div class="header-right" @click="closeModal()"><i class="iconfont fs22">&#xea7f;</i></div>
            </div>
            <div class="modal-body">
              <div>
                <div class="ipt-title"><span class="required">*</span>名称</div>
                <div><input type="text" v-model="brandForm.brandName" maxlength="50" placeholder="请输入名称" class="ipt" /></div>
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>编码</div>
                <div><input type="text" v-model="brandForm.brandCode" maxlength="10" placeholder="请输入编码" class="ipt" /></div>
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>首字母</div>
                <div><input type="text" v-model="brandForm.fstChar" maxlength="10" placeholder="请输入品牌首字母" class="ipt" /></div>
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>排序</div>
                <div><input type="number" v-model="brandForm.sort" maxlength="30" placeholder="请输入排序" class="ipt" /></div>
              </div>
              <div>
                <div class="ipt-title">LOGO</div>
                <upload :kind="1" :types="1" :file="logoRef" @setUrl="setUrl" />
              </div>
              <div>
                <div class="ipt-title">描述</div>
                <div><textarea v-model="brandForm.remarks" class="desc-txt"></textarea></div>
              </div>
            </div>
            <div class="modal-footer">
              <div class="btn-pi mr15" @click="save"><i class="iconfont">&#xea90;</i> 保存</div>
              <div class="btn-d" @click="closeModal"><i class="iconfont">&#xea4f;</i> 取消</div>
            </div>
          </div>
        </c-scrollbar>
      </div>
    </transition>
    <loader :loadShow="loadShow" />
  </div>
</template>

<style scoped>
.brand-a {padding: 10px;}
.brand-b {padding: 0 20px 10px 20px; display: flex; display: -webkit-flex;}
.brand-c {display: inline-flex; display: -webkit-inline-flex;}
.brand-d {flex-grow: 1; text-align: right; padding-top: 10px; color: #666;}
.brand-e {border: 1px dashed #DDD; padding: 5px 15px 15px 15px; display: flex; display: -webkit-flex; flex-wrap: wrap; margin-bottom: 10px;}
.brand-f {display: inline-flex; display: -webkit-inline-flex;}
</style>